<template>
  <div>
    <span @click="onShowLeaveMessageDrawer">
      <slot></slot>
    </span>

    <el-drawer
      destroy-on-close
      append-to-body
      direction="rtl"
      show-close
      v-model="leaveMessageDrawerVisible"
      size="22%"
    >
      <template #header>
        <div style="display: flex; gap: 8px; align-items: center; font-size: 14px; color: #303133">
          工单编号:{{ workNo }}
          <el-icon size="16" title="刷新" style="cursor: pointer" @click="getList">
            <Refresh />
          </el-icon>
        </div>
      </template>
      <div class="left_side">
        <!-- @scroll="checkScroll" -->
        <div class="item_li" ref="chatContentBoxs">
          <div
            class="load_more"
            v-if="Number(total) / 10 > currentPage && Number(total) > 10"
            @click="getloadMoreData"
          >
            加载更多数据
          </div>
          <div class="on_more" v-if="Number(total) / 10 < currentPage && Number(total) > 10"
            >没有更多了</div
          >
          <div v-for="(item, index) in activeList" :key="index" class="li_c">
            <div class="oneself_c" v-if="item.empId === UserStore.userInfo.id">
              <div
                class="item_c"
                v-if="!(index > 0 && item.createTime === activeList[index - 1].createTime)"
              >
                {{ item.createTime }}
              </div>
              <div class="top_note" v-if="item.content || item.annexs.length > 0">
                <div class="user">
                  <!--用户名-->
                  <p class="item_name">{{ item.emp }}</p>

                  <!--头像-->
                  <el-image class="avatar" fit="contain" :src="item.avatar ? item.avatar : image" />
                </div>

                <div class="content_c">
                  <!--内容-->
                  <div class="text_c" v-if="item.content">
                    <span v-html="item.content.replace(/\n/g, '<br/>')"></span>
                  </div>

                  <div v-if="item.annexs.length > 0" class="img_container">
                    <!--图片-->
                    <el-image
                      v-for="(img, imgIndex) in item.annexs"
                      :key="imgIndex"
                      class="img_c"
                      :lazy="true"
                      fit="contain"
                      style="
                        width: 100px;
                        height: 100px;
                        border: 1px solid #ebeef5;
                        border-radius: 4px;
                        box-sizing: border-box;
                        padding: 12px;
                      "
                      :initial-index="imgIndex"
                      :preview-src-list="item.annexs"
                      :src="img"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div
                class="item_c"
                v-if="!(index > 0 && item.createTime == activeList[index - 1].createTime)"
              >
                {{ item.createTime }}
              </div>
              <div class="top_note" v-if="item.content || item.annexs.length > 0">
                <div class="user">
                  <!--头像-->
                  <el-image
                    :size="24"
                    class="avatar"
                    fit="contain"
                    :src="item.avatar ? item.avatar : image"
                  />

                  <!--用户名-->
                  <p class="item_name">{{ item.emp }}</p>
                </div>

                <div class="content_c">
                  <!--内容-->
                  <div class="text_c">
                    <span v-html="item.content.replace(/\n/g, '<br/>')"></span>
                  </div>

                  <!--图片-->
                  <div class="img_container">
                    <el-image
                      v-for="(img, imgIndex) in item.annexs"
                      :key="imgIndex"
                      class="img_c"
                      fit="contain"
                      style="
                        width: 100px;
                        height: 100px;
                        border: 1px solid #ebeef5;
                        border-radius: 4px;
                        box-sizing: border-box;
                        padding: 12px;
                      "
                      :lazy="true"
                      :preview-src-list="item.annexs"
                      :src="img"
                      :initial-index="imgIndex"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <el-empty v-if="activeList.length == 0" description="暂无留言" />
        </div>
      </div>
      <template #footer>
        <div class="footer">
          <div class="content_send_upload" v-if="!$route.query.isArchive">
            <div
              @focus="scrollHeight()"
              @blur="contentBlur"
              ref="contenteditableInputs"
              placeholder="发送留言..."
              class="content"
              contenteditable="true"
            ></div>
            <!-- <div class="btn_group flex-justify-end"> -->
            <div class="flex-justify-end">
              <!-- <el-upload :show-file-list="false" accept="image/*" :on-change="handleChange" :auto-upload="false"
                multiple>
                <el-button size="large" link :icon="FolderOpened" />
              </el-upload> -->
              <HLink @click="sendInfoAction">发送</HLink>
            </div>
          </div>

          <el-checkbox-group v-model="data.visitTypes" class="visit_type">
            <el-checkbox :value="0"><span class="visit_type_text">公开</span></el-checkbox>
            <el-checkbox :value="1"><span class="visit_type_text">服务商可见</span></el-checkbox>
            <el-checkbox :value="2"><span class="visit_type_text">工程师可见</span></el-checkbox>
            <el-checkbox :value="3"><span class="visit_type_text">后台可见</span></el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, toRefs, reactive, onUnmounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { getWorkLeaveMessageList, saveWorkLeaveMessage } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'
  import { useUserStore } from '@/store/modules/user'
  import image from '@/assets/image/avatar.png'
  import { Refresh } from '@element-plus/icons-vue'
  import { LeaveMessage } from './types'
  import HLink from '@/components/common/link/HLink.vue'

  const props = defineProps({
    workId: [String, Array],
    workNo: String,
  })

  const chatContentBoxs = ref<HTMLDivElement | null>(null)
  const { workId, workNo } = toRefs(props)

  // 操作日志数据
  const activeList = ref<Array<LeaveMessage>>([])
  const total = ref(0)
  let pageSize = ref(10)
  let currentPage = ref(1)
  const UserStore = useUserStore()
  const route = useRoute()
  let data = reactive({
    annex: [],
    content: '',
    visitTypes: [0],
    workId: workId.value,
  })

  // 抽屉显示状态
  const leaveMessageDrawerVisible = ref(false)

  const imageUrls = ref([])
  // 获取图片
  // const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
  //   if (imageUrls.value.length >= 10) {
  //     ElMessage({
  //       message: '最多可以上传十个文件',
  //       type: 'error',
  //     })
  //     return
  //   }
  //   let img = URL.createObjectURL(uploadFile.raw)
  //   imageUrls.value.push(uploadFile.raw)
  //   const value = contenteditableInputs.value
  //   let image = new Image()
  //   image.src = img
  //   image.title = uploadFile.uid.toString()
  //   image.width = 40
  //   image.onload = function () {
  //     value.appendChild(image)
  //     keepLastIndex && keepLastIndex(value)
  //   }
  // }

  const range = ref<Range | null>(null)
  const selection = ref<Selection | null>(null)
  const contenteditableInputs = ref<HTMLDivElement | null>(null)
  const contentBlur = () => {
    /**
     * 每次焦点移出都要保存一次当前 range ，后面好放回来
     * 由于输入框以外的点击都会使输入框失去焦点，不知道会有什么操作，故勤保存
     */
    // range.value = selection.value.getRangeAt(0)
  }
  const focusContentEditable = () => {
    // const editor = contenteditableInputs.value
    // editor?.focus()
    // // 获取选中的元素
    // selection.value = document.getSelection()
    // range.value = selection.value.getRangeAt(0)
  }
  const keepLastIndex = (obj) => {
    if (window.getSelection) {
      obj.focus() // 解决ff不获取焦点无法定位问题
      let range = window.getSelection() // 创建range
      range.selectAllChildren(obj) // range 选择obj下所有子内容
      range.collapseToEnd() // 光标移至最后
    }
  }
  // 滚动到底部
  const scrollHeight = () => {
    setTimeout(() => {
      if (chatContentBoxs.value) {
        chatContentBoxs.value.scrollTop = chatContentBoxs.value.scrollHeight
      }
    }, 100)
  }
  // 键盘事件处理函数
  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Enter') {
      event.preventDefault() // 阻止默认换行（可选）
      sendInfoAction() // 调用发送函数
    }
  }

  // 发送
  const sendInfoAction = async () => {
    // 获取去除首尾空格的内容
    let value = contenteditableInputs.value.innerHTML.trim()

    if (!value) {
      return ElMessage.error('请填写发送内容')
    }
    let img = []
    let imgIds = []
    let txt = /<div.*?>(.*?)<\/div>/gi
    let reg1 = /<img.*?title="(.*?)".*?>/gi
    let flag = value.match(reg1)
    if (value.match(txt)) {
      value = value.replace(txt, (item, $item) => {
        //找到图片做标书
        if ($item == '<br>') {
          return `\n`
        } else {
          return `\n${$item}`
        }
      })
    }
    // 过滤图片进行分割
    if (flag) {
      let content2 = value.replace(reg1, (item, $1) => {
        //找到图片做标书
        imgIds.push($1)
        return ``
      })
      imageUrls.value.filter((o) => {
        imgIds.filter((i) => {
          if (o.uid) {
            if (o.uid == i) {
              img.push(o)
            }
          } else {
            if (new Date(o.lastModifiedDate).getTime() == i) {
              img.push(o)
            }
          }
        })
      })
      data.content = content2
    } else {
      data.content = value
    }
    if (img.length > 0) {
      const res = await orderAnnexUpload(img)
      if (res.data.code === 20000) {
        data.annex = res.data.data.rows
        await saveWorkLeave()
      }
    } else {
      await saveWorkLeave()
    }
    data.annex = []
  }

  const emits = defineEmits(['updated'])
  /**
   * 保存留言
   */
  async function saveWorkLeave() {
    const res = await saveWorkLeaveMessage(data)
    if (res.data.code == 20000) {
      await getList()
      scrollHeight() //滚动到底部
      contenteditableInputs.value.innerHTML = ''
      imageUrls.value = []
      emits('updated')
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
        })
    }
  }

  /**
   * 获取更多
   */
  function getloadMoreData() {
    currentPage.value += 1
    if (Number(total.value) / 10 > currentPage.value) {
      let data = {
        limit: pageSize.value,
        page: currentPage.value,
      }
      getWorkLeaveMessageList(data, workId.value).then((res) => {
        if (res.data.success) {
          activeList.value = [...res.data.data.rows, ...activeList.value]
          total.value = Number(res.data.data.total)
          nextTick(() => {
            setTimeout(() => {
              chatContentBoxs.value.scrollTop = 600
            }, 0)
          })
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
            })
        }
      })
    }
  }
  // 获取留言列表
  async function getList() {
    const res = await getWorkLeaveMessageList({ limit: 10, page: 1 }, workId.value)
    if (res.data.success) {
      activeList.value = res.data.data.rows
      total.value = Number(res.data.data.total)
      nextTick(() => {
        scrollHeight()
      })
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
    }
  }

  // 复制粘贴
  async function handlePaste(event) {
    const items = event.clipboardData?.items
    const clipboardData = event.clipboardData
    const pastedText = clipboardData.getData('text')
    //   粘贴的文本
    // if (pastedText) {
    event.preventDefault() // 阻止默认粘贴行为
    contenteditableInputs.value.innerHTML += pastedText
    // }
    // if (items) {
    //   // 粘贴的图片
    //   for (const item of items) {
    //     if (item.type.indexOf('image') !== -1) {
    //       event.preventDefault() // 阻止默认粘贴行为
    //       const file = await item.getAsFile()
    //       let time = new Date(file.lastModifiedDate).getTime()
    //       imageUrls.value.push(file)

    //       // 创建一个新的图片元素
    //       const img = new Image()

    //       // 设置图片属性
    //       img.src = URL.createObjectURL(file)
    //       img.title = time.toString()
    //       img.width = 40
    //       img.onload = function () {
    //         contenteditableInputs.value.appendChild(img)
    //         keepLastIndex && keepLastIndex(contenteditableInputs.value)
    //       }
    //     }
    //   }
    // }
  }

  /**
   * 显示抽屉事件
   */
  const onShowLeaveMessageDrawer = async () => {
    leaveMessageDrawerVisible.value = true
    await getList()
    if (!route.query.isArchive) {
      await nextTick()
      focusContentEditable()
      contenteditableInputs.value.addEventListener('paste', handlePaste) // 监听粘贴事件
      contenteditableInputs.value.addEventListener('keydown', handleKeyDown) // 新增：绑定键盘事件
    }
  }

  // 组件卸载时移除事件监听（避免内存泄漏）
  onUnmounted(() => {
    if (contenteditableInputs.value) {
      contenteditableInputs.value.removeEventListener('keydown', handleKeyDown)
    }
  })
</script>
<style lang="scss" scoped>
  .left_side {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    .item_li {
      height: 100vh;
      overflow-y: auto;
      margin: 0 10px;
      width: 100%;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;

      /* IE 10+ */
      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      .load_more {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 11px;
        margin-bottom: 12px;

        &:hover {
          color: #007cff;
          cursor: pointer;
        }
      }

      .on_more {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 11px;
        margin-bottom: 12px;
      }

      .li_c {
        .item_c {
          position: relative;
          right: 50%;
          transform: translateX(50%);
          font-size: 10px;
          color: #999;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .oneself_c {
          display: flex;
          flex-direction: column;
          align-items: flex-end;

          .top_note {
            display: flex;
            align-items: end;
            flex-direction: row-reverse;
            flex-direction: column;
            width: 100%;

            .content_c {
              max-width: 300px;
              margin: 8px 30px 20px 0;
              display: flex;
              flex-direction: column;
              gap: 4px;
              align-items: flex-end;

              .text_c {
                padding: 5px 8px;
                color: #333;
                white-space: pre-wrap;
                font-size: 12px;
                background-color: #e2e7f7;
                border-radius: 6px 0 6px 6px;
                display: inline-block;
              }

              .img_container {
                display: grid;
                grid-template-columns: auto;
                row-gap: 4px;
              }
            }

            .item_name {
              margin-right: 5px;
              font-size: 12px;
              color: #666;
            }
          }
        }

        .top_note {
          .user {
            display: flex;
            align-items: center;

            .avatar {
              width: 30px;
              height: 30px;
              border-radius: 50%;
            }

            .item_name {
              margin-left: 5px;
              font-size: 12px;
              color: #666;
            }
          }

          .content_c {
            margin: 8px 0 20px 30px;
            display: flex;
            flex-direction: column;
            gap: 4px;
            max-width: 300px;
            align-items: flex-start;

            .text_c {
              padding: 5px 8px;
              color: #333;
              white-space: pre-wrap;
              font-size: 12px;
              background-color: #e2e7f7;
              border-radius: 0 6px 6px 6px;
              // box-shadow: 0 0 1px 1px #00000022;
              word-wrap: break-word;
              word-break: break-all;
              display: inline-block;
            }

            .img_container {
              display: grid;
              grid-template-columns: auto;
              row-gap: 4px;
            }
          }
        }
      }
    }

    .chatInput {
      width: 100%;
      box-sizing: border-box;
    }
  }

  .f_content {
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;

    .upload_send {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 8px;

      .btn_send {
        color: #00c0c0;
        font-size: 12px;
        cursor: pointer;
        margin-left: 8px;

        &:hover {
          color: #00c0c0ab;
        }
      }

      .btn_uploading {
        cursor: pointer;
        font-size: 16px;
      }
    }

    :deep(.el-textarea .el-input__count) {
      right: 40px;
    }

    [contenteditable]:focus {
      outline: none;
    }

    [contenteditable]:empty:before {
      content: attr(placeholder);
      color: #cccccc;
      font-size: 12px;
    }
  }

  .footer {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .content_send_upload {
      display: flex;
      flex-direction: column;
      gap: 8px;

      div.content {
        white-space: pre-wrap;
        font-size: 12px;
        word-wrap: break-word;
        word-break: break-all;
        display: inline-block;
        background-color: #f2f3f5;
        border-radius: 4px;
        box-sizing: border-box;
        padding: 8px;
        height: 120px;
        text-align: left;
        outline: none;
        overflow: auto;
      }

      div.content:empty:before {
        content: attr(placeholder);
        color: #a8abb2;
      }

      .btn_group {
        display: flex;
        justify-content: space-between;
      }
    }

    .visit_type {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      .visit_type_text {
        color: #000;
      }

      :deep(.el-checkbox) {
        height: 18px;
        margin: 0 !important;

        .el-checkbox__label {
          transform: scale(0.9);
          font-size: 12px;
          padding: 0;
        }
      }
    }
  }
</style>
